package com.example.onlinemusicserver2024.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.onlinemusicserver2024.common.R;
import com.example.onlinemusicserver2024.mapper.SingerMapper;
import com.example.onlinemusicserver2024.model.domain.Singer;
import com.example.onlinemusicserver2024.service.SingerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.List;

@Service
public class SingerServiceImpl extends ServiceImpl<SingerMapper, Singer> implements SingerService {
    @Autowired
    SingerMapper singerMapper;

    @Override
    public R allSinger(Integer sex) {
        //判断是否需要设置性别的查询条件
        QueryWrapper<Singer> queryWrapper = null;
        if (sex != null && sex != -1) {// sex=-1表示查询全部歌手
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sex", sex);
        }
        List<Singer> lstSinger = singerMapper.selectList(queryWrapper);
        return R.success("查询成功", lstSinger);
    }

    @Override
    public R addSinger(Singer singer) {
        // 设置默认的头像
        singer.setPic("https://java-pp.oss-cn-hangzhou.aliyuncs.com/img/singerPic/user.jpg");
        int count = singerMapper.insert(singer);
        if (count > 0) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }
    }

    /**
     * 更新歌手信息
     *
     * @param singer
     * @return
     */
    @Override
    public R updateSinger(Singer singer) {
        // 严谨的操作：先检验该数据是否存在，如果存在再去更新，如果不存在则给出相应的提示
        // 1.先查询数据库中是否有该条数据
        int singerId = singer.getId();
        Singer s = singerMapper.selectById(singerId);
        if (s != null) {//表示有数据，可以更新
            BeanUtils.copyProperties(singer, s);
            int count = singerMapper.updateById(s);
            if (count > 0) {
                return R.success("更新成功");
            } else {
                return R.error("更新失败");
            }
        } else {
            //没有查询到数据，无法更新
            return R.error("数据不存在，请确认");
        }
    }

    @Override
    public R deleteSinger(int id) {
        // 先判断数据是否存在
        Singer singer = singerMapper.selectById(id);
        if (singer != null) {
            if (singerMapper.deleteById(id) > 0) {
                return R.success("删除成功");
            } else {
                return R.error("删除失败");
            }
        } else {
            return R.error("数据不存在，请确认");
        }
    }
}
